package com.example.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

/**
 * MyScreenshot：获取当前屏幕截图并返回 Base64
 * 支持 Android 28+，适用于 MediaProjection API
 */
public class MyScreenshot {

    private final Context context;
    private final MediaProjection mediaProjection;

    public MyScreenshot(Context context, MediaProjection mediaProjection) {
        this.context = context;
        this.mediaProjection = mediaProjection;
    }

    public void captureScreen(Callback callback) {
        if (mediaProjection == null) {
            if (callback != null) callback.onFailed("MediaProjection 未初始化");
            return;
        }

        Handler handler = new Handler(Looper.getMainLooper());

        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (wm != null) wm.getDefaultDisplay().getRealMetrics(metrics);

        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        int density = metrics.densityDpi;

        ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 1);

        mediaProjection.createVirtualDisplay(
                "MyScreenshot",
                width,
                height,
                density,
                0,
                imageReader.getSurface(),
                null,
                handler
        );

        handler.postDelayed(() -> {
            Image image = imageReader.acquireLatestImage();
            if (image != null) {
                Bitmap bitmap = convertImageToBitmap(image);
                image.close();
                imageReader.close();

                if (bitmap != null) {
                    String base64 = bitmapToBase64(bitmap);
                    if (callback != null) callback.onSuccess(base64);
                } else {
                    if (callback != null) callback.onFailed("获取 Bitmap 失败");
                }
            } else {
                if (callback != null) callback.onFailed("Image 为空");
            }
        }, 200);
    }

    private Bitmap convertImageToBitmap(Image image) {
        Image.Plane[] planes = image.getPlanes();
        if (planes.length <= 0) return null;
        ByteBuffer buffer = planes[0].getBuffer();
        int width = image.getWidth();
        int height = image.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        return bitmap;
    }

    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    public interface Callback {
        void onSuccess(String base64);
        void onFailed(String error);
    }
}
